#!/bin/bash
# sh check_branch_diff_old.sh -envJsonF "${EnvironmentFILE_PATH}" --last-package-json-file "${lastPackageInfoFilePath}" --develop-branchs-json-file "${Develop_Branchs_FILE_PATH}" --history-version-json-file "${History_Versions_FILE_PATH}" --product-personnel-json-file "${Product_Personnel_FILE_PATH}"
:<<!
检查本分支的本次打包是否漏掉本分支上次打包的分支
!

#lastPackageInfoFilePath="../../app_branch_info.json"
#Develop_Branchs_FILE_PATH="../example_packing_info/app_branch_info.json"
#History_Versions_FILE_PATH="../example_packing_info/app_history_version.json"
#Product_Personnel_FILE_PATH="../example_packing_info/app_product_personnel.json"


# shell 参数具名化
show_usage="args: [-envJsonF, -lastJsonF, -devJsonF, -hisJsonF, -peoJsonF]\
                                  [--environment-json-file=, --last-package-json-file=, --develop-branchs-json-file=, --history-version-json-file=, --product-personnel-json-file=]"

while [ -n "$1" ]
do
        case "$1" in
                -envJsonF|--environment-json-file) EnvironmentFILE_PATH=$2; shift 2;;
                -lastJsonF|--last-package-json-file) lastPackageInfoFilePath=$2; shift 2;;
                -devJsonF|--develop-branchs-json-file) Develop_Branchs_FILE_PATH=$2; shift 2;;
                -hisJsonF|--history-version-json-file) History_Versions_FILE_PATH=$2; shift 2;;
                -peoJsonF|--product-personnel-json-file) Product_Personnel_FILE_PATH=$2; shift 2;;
                --) break ;;
                *) echo $1,$2,$show_usage; break ;;
        esac
done

JQ_EXEC=`which jq`

echo "$0检查本分支上个包和和本分支此次包的需求包含"

CurrentDirName=${PWD##*/}

# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
#echo "CurrentDIR_Script_Absolute=${CurrentDIR_Script_Absolute}"
#bulidScriptCommon_dir_Absolute=${CurrentDIR_Script_Absolute}/..
bulidScriptCommon_dir_Absolute=${CurrentDIR_Script_Absolute%/*} # 使用此方法可以避免路径上有..
#echo "bulidScriptCommon_dir_Absolute=${bulidScriptCommon_dir_Absolute}"

qscript_path_get_filepath="${bulidScriptCommon_dir_Absolute}/qscript_path_get.sh"
qbase_update_json_file_singleString_script_path="$(sh ${qscript_path_get_filepath} qbase update_json_file_singleString)"

source ${bulidScriptCommon_dir_Absolute}/a_function.sh ${bulidScriptCommon_dir_Absolute} # 为了使用 updatePackageErrorCodeAndMessage
check_jsonFile_valid ${Develop_Branchs_FILE_PATH}



# 检查新文件的打包分支相比旧文件是否有缺失
function checkHasMissingBranchDiffOld() {
    while [ -n "$1" ]
    do
            case "$1" in
                    -curBranchJsonF|--current-branch-json-file) Develop_Branchs_FILE_PATH=$2; shift 2;;
                    -oldBranchJsonF|--old-branch-json-file) lastPackageInfoFilePath=$2; shift 2;;
                    --) break ;;
                    *) echo $1,$2,$show_usage; break ;;
            esac
    done
    
    allContainBranchArray=$(cat "${Develop_Branchs_FILE_PATH}" | ${JQ_EXEC} '.package_merger_branchs') # -r 去除字符串引号
    #echo "allContainBranchArray=${allContainBranchArray}"
    if [ -z "${allContainBranchArray}" ] || [ "${allContainBranchArray}" == "null" ]; then
        allContainBranchArray="" # null" 也设置成空字符串
        echo "❌Error:未找到当前分支合入的其他分支信息，将退出allContainBranchArray=${allContainBranchArray}"
        return 1
    fi

    allContainBranchNames=$(cat "${Develop_Branchs_FILE_PATH}" | ${JQ_EXEC} '.package_merger_branchs' | ${JQ_EXEC} -r '.[].name') # -r 去除字符串引号
    allContainBranchNames=($allContainBranchNames) # 此时才是真正的数组
    echo "本分支【本次打包】包含的分支功能allContainBranchNames值如下:\n${allContainBranchNames[*]}\n"
    
    if [ -f "${lastPackageInfoFilePath}" ]; then # lastPackageInfoFilePath 加引号，避免名称中有空格，导致的错误
        echo "文件存在，即代表当前包在上线包之后已经有打过包了，所以要检查下新的包是否都包含了之前的包的需求功能，防止漏掉出现测试bug重新打开问题"
        
        #[在shell脚本中验证JSON文件的语法](https://qa.1r1g.com/sf/ask/2966952551/)
        lastPackageInfoFileJsonString=$(cat "${lastPackageInfoFilePath}" | json_pp) # 文件名加引号，加引号，避免名称中有空格，导致的错误
        #echo "lastPackageInfoFileJsonString=${lastPackageInfoFileJsonString}"
        lastPackageInfoFileJsonLength=${#lastPackageInfoFileJsonString}
        #echo "lastPackageInfoFileJsonLength=${#lastPackageInfoFileJsonLength}"
        if [ ${lastPackageInfoFileJsonLength} == 0 ]; then
            echo "${lastPackageInfoFilePath}不是标准的json格式，弃用，不用检查新包是否包含旧包"
        else
            lastFeatureBranceNamesArray=$(cat "${lastPackageInfoFilePath}" | ${JQ_EXEC} '.package_merger_branchs' | ${JQ_EXEC} -r '.[].name') # -r 去除字符串引号
            lastFeatureBranceNamesArray=($lastFeatureBranceNamesArray) # 此时才是真正的数组
            echo "本分支【上次打包】包含的分支功能lastFeatureBranceNamesArray值如下:\n${lastFeatureBranceNamesArray[*]}\n"
            lastFeatureBranceNameCount=${#lastFeatureBranceNamesArray[@]}

            for ((i=0;i<lastFeatureBranceNameCount;i++))
            do
                devBranchName=${lastFeatureBranceNamesArray[i]}
                if [ ${i} -gt 0 ]; then
                    echo "\n"
                fi
                if [[ "${allContainBranchNames[*]}" =~ ${devBranchName} ]]; then
                    echo "恭喜:新包包含旧包的${devBranchName}"
                else
                    echo "抱歉:新包缺失旧包的${devBranchName}"
                    missingContainBranchNameArray[${#missingContainBranchNameArray[@]}]=${devBranchName}
                fi
            done
            
           if [ -n "${missingContainBranchNameArray}" ]; then
                current_searchFromDateString=$(cat ${Develop_Branchs_FILE_PATH} | ${JQ_EXEC} -r ".package_merger_branchs_searchFromDateString")
                old_searchFromDateString=$(cat ${lastPackageInfoFilePath} | ${JQ_EXEC} -r ".package_merger_branchs_searchFromDateString")
                echo "old_searchFromDateString=${old_searchFromDateString}"
                echo "current_searchFromDateString=${current_searchFromDateString}"
                if [ "${current_searchFromDateString}" != "${old_searchFromDateString}" ]; then # lastPackageInfoFilePath 加引号，避免名称中有空格，导致的错误
                    echo "您当前打包的需求较上次有所缺失，缺失分支${#missingContainBranchNameArray[@]}个,如下:${missingContainBranchNameArray[*]}。但由于此次打包是上次上线代码合并${current_searchFromDateString}后的第一次打包，所以会进一步检查所漏分支是不是因为已经上线。(排查方法:所漏分支在最后一个版本里)"
                    
                    lastOnlineVersionMapString=$(cat ${History_Versions_FILE_PATH} | ${JQ_EXEC} -r '.history_versions[0]' ) # -r 去除字符串引号
                    lastVersionFeatureBranceNamesArray=$(echo "${lastOnlineVersionMapString}" | ${JQ_EXEC} '.online_brances' | ${JQ_EXEC} -r '.[].name') # -r 去除字符串引号
                    lastVersionFeatureBranceNamesArray=($lastVersionFeatureBranceNamesArray) # 此时才是真正的数组
                    lastVersionFeatureBranceNamesCount=${#lastVersionFeatureBranceNamesArray[@]}
                    echo "最后上线的版本有${lastVersionFeatureBranceNamesCount}个分支,分别如下lastVersionFeatureBranceNamesArray=${lastVersionFeatureBranceNamesArray[*]}"
                    
                    missingContainBranchNameCount=${#missingContainBranchNameArray[@]}
                                     
                    for ((i=0;i<missingContainBranchNameCount;i++))
                    do
                        mayMissingBranchName=${missingContainBranchNameArray[i]}
                        if [ ${i} -gt 0 ]; then
                            echo "\n"
                        fi
                        if [[ "${lastVersionFeatureBranceNamesArray[*]}" =~ ${mayMissingBranchName} ]]; then
                            echo "恭喜:新包相比旧包丢失的${mayMissingBranchName}已上线"
                        else
                            echo "抱歉:新包相比旧包丢失的${mayMissingBranchName}未上线"
                            realMissingContainBranchNameArray[${#realMissingContainBranchNameArray[@]}]=${mayMissingBranchName}
                        fi
                    done
                else
                    echo "您当前打包的需求较上次有所缺失，缺失分支${#missingContainBranchNameArray[@]}个,如下:${missingContainBranchNameArray[*]}。且由于此次打包不是上次上线代码合并${current_searchFromDateString}后的第一次打包，所以不会进一步检查所漏分支是不是因为已经上线。(排查方法:所漏分支在最后一个版本里)"
                    realMissingContainBranchNameArray=${missingContainBranchNameArray}
                fi
            else
                realMissingContainBranchNameArray=${missingContainBranchNameArray}
            fi
            
            if [ -n "${realMissingContainBranchNameArray}" ]; then
                PackageErrorCode=-1
                PackageErrorMessage="您当前打包的需求较上次有所缺失，请先补全，再打包，缺失分支${#realMissingContainBranchNameArray[@]}个,如下:${realMissingContainBranchNameArray[*]}。"
                PackageErrorMessage+="可能原因如下:这些分支未合并进来，或者是其有新的提交也会造成这个问题。"
                PackageErrorMessage+="具体信息如下:之前分支功能有${lastFeatureBranceNamesArray[*]}。而现在功能是${allContainBranchNames[*]}。"
                PackageErrorMessage+="【附：如果某个分支已确实不需要使用。可以前往${lastPackageInfoFilePath}删除.package_merger_branchs中的那个分支】"
                updatePackageErrorCodeAndMessage ${PackageErrorCode} "${PackageErrorMessage}"
                
                realMissingContainBranchNameCount=${#realMissingContainBranchNameArray[@]}
                for ((i=0;i<realMissingContainBranchNameCount;i++))
                do
                    realMissingBranchName=${realMissingContainBranchNameArray[i]}
                    echo "正在执行命令(获取指定本地分支最后一次提交的用户)：《git show --format=%aN -b origin/\"${realMissingBranchName}\" -s》"
                    branchLastCommitUserName=$(git show --format=%aN -b origin/"${realMissingBranchName}" -s)
                    # echo "正在执行命令(获取指定远程分支最后一次提交的用户，有些分支返回正常，有些分支失败)：《git ls-remote --heads \"${realMissingBranchName}\" | cut -f 1 | xargs -I {} git show --format=%aN {} -s | head -n 1》"
                    # branchLastCommitUserName=$(git ls-remote --heads "${realMissingBranchName}" | cut -f 1 | xargs -I {} git show --format=%aN {} -s | head -n 1)
                    
                    # [jq --arg传递的变量select()没有硬编码值就不能工作吗？](https://cloud.tencent.com/developer/ask/sof/355822/answer/594723)
                    Product_Personnel_Array=$(cat ${Product_Personnel_FILE_PATH} | ${JQ_EXEC} -r '.[]') # -r 去除字符串引号
                    # echo ${Product_Personnel_Array} | ${JQ_EXEC} -r --arg branchLastCommitUserName "$branchLastCommitUserName" 'select(.git_name=="qian")' 
                    # echo ${Product_Personnel_Array} | ${JQ_EXEC} -r --arg branchLastCommitUserName "$branchLastCommitUserName" 'select(.git_name==$branchLastCommitUserName)'
                    CurrentBranch_Personnel_Map=$(echo ${Product_Personnel_Array} | ${JQ_EXEC} -r --arg branchLastCommitUserName "$branchLastCommitUserName" 'select(.git_name==$branchLastCommitUserName)') # -r 去除字符串引号
                    CurrentBranch_Personnel_Uid=$(echo ${CurrentBranch_Personnel_Map} | ${JQ_EXEC} -r '.uid') # -r 去除字符串引号
                    realMissingBranchUidArray[${#realMissingBranchUidArray[@]}]=${CurrentBranch_Personnel_Uid}
                done
                
                echo "正在执行命令(修改打包错误的@人员)：《sh ${qbase_update_json_file_singleString_script_path} -jsonF ${EnvironmentFILE_PATH} -k 'package_notification_argument_current.wechat.error.mentioned_list' -v \"${realMissingBranchUidArray[*]}\"》"
                sh ${qbase_update_json_file_singleString_script_path} -jsonF ${EnvironmentFILE_PATH} -k 'package_notification_argument_current.wechat.error.mentioned_list' -v "${realMissingBranchUidArray[*]}"

                return 1
            fi
        fi
    else
        echo "${lastPackageInfoFilePath}文件不存在，代表当前包是上线包之后的第一次打包"
    fi
}

checkHasMissingBranchDiffOld -curBranchJsonF "${Develop_Branchs_FILE_PATH}" -oldBranchJsonF "${lastPackageInfoFilePath}"
if [ $? != 0 ]; then
    exit_script
fi

echo "更新本次打包的内容到项目外和项目内，便于下次检查"
cp "${Develop_Branchs_FILE_PATH}" "${lastPackageInfoFilePath}"
